<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="初始化库存" @ok="handleSubmit" width="500px" destroyOnClose>
    <BasicTable @register="registerTable">
      <template #stock="{ record }">
        <InputNumber style="width: 80%" v-model:value="record.stock" />
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { InputNumber } from "ant-design-vue"
  import { initStockColumns } from "./goods.data"
  import { BasicTable, TableAction } from "/@/components/Table"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { listStore } from "/@/api/misc/store"

  // 声明Emits
  const emit = defineEmits(["register", "success"])
  const initStockMap = ref<Map<String, Number>>(new Map())
  const { tableContext } = useListPage({
    tableProps: {
      api: listStore,
      afterFetch: (data) => {
        // 初始化库存为0
        data?.forEach((e) => {
          const info = initStockMap.value.get(e.id)
          e.stock = info ? info : 0
        })
      },
      immediate: false,
      columns: initStockColumns,
      size: "small",
      pagination: false,
      striped: true,
      useSearchForm: false,
      showTableSetting: false,
      canResize: false,
      bordered: false,
      showIndexColumn: false,
      tableSetting: { fullScreen: true },
      showActionColumn: false,
    },
  })
  //注册table数据
  const [registerTable, { reload, getForm, getDataSource }] = tableContext
  // 这个id不存在, 只是前端用于标识行数据便于处理
  const tempId = ref("")
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    console.log("record", data.record)
    initStockMap.value.clear()
    data.record?.stockList?.forEach((e) => {
      initStockMap.value.set(e.storeId, e.stock)
    })

    tempId.value = data.record.tempId
    //重置表单
    setModalProps({ confirmLoading: false, canFullscreen: false, draggable: false, height: 300 })
    reload()
  })

  async function handleSubmit(v) {
    try {
      const tableData = getDataSource()
      const data = tableData.map((e) => ({ storeId: e.id, stock: e.stock }))
      console.log("tableData", data)
      setModalProps({ confirmLoading: true })
      closeModal()
      emit("success", unref(tempId), data)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
